<?php

$plugin_info = array(
  'pi_name' => 'Paginatee',
  'pi_version' => '1.0',
  'pi_author' => 'Victor Gutierrez',
  'pi_author_url' => 'http://www.trulyee.com',
  'pi_description' => 'Lets you paginate an entry with table of contents (page titles)',
  'pi_usage' => Paginatee::usage()
  );

class Paginatee
{

var $return_data = "";

  function Paginatee()
  {
    global $TMPL, $SESS, $FNS;
    
    // grab paramaters
  	$current = $TMPL->fetch_param('current') ? $TMPL->fetch_param('current')     : '';
    
                  
	/*
	 * Lets see if they added {pgnt_titles} and {pgnt_text} variable pair
	 * If they did put them into an variable of the same name.
	 */
	$pgnt_text = $TMPL->fetch_data_between_var_pairs($TMPL->tagdata, "pgnt_text");		// echo $pgnt_text;
	$pgnt_titles = $TMPL->fetch_data_between_var_pairs($TMPL->tagdata, "pgnt_titles");	// echo $pgnt_titles;
	
	
	/*
	 * If they added the {pgnt_text} variable pair lets do our stuff
	 */
	if ($pgnt_text)
	{
		// Find {pagebebreak} variables (ex. {pagebreak:My First Page} )
		preg_match_all("/{pagebreak:.*?}/", $pgnt_text, $pagebreak_matches);		// print_r($pagebreak_matches);
		$pages_amount = count($pagebreak_matches[0]);								// echo $pages_amount;
		
		// If they added {pagebreak} variable lets do our stuff.
		if ($pages_amount > 0)
		{
			// If something is found
            // Fetch the titles out of the pagebreaks variables and put them into an array
        	foreach ($pagebreak_matches[0] as $value) 
        	{
        	    $page_titles[] = substr($value, 11, -1); 
        	} 	// print_r($page_titles);        	
        	        	
            // Remove the titles from the pagebreak
        	$pgnt_text = preg_replace($pagebreak_matches[0], "pagebreak", $pgnt_text);	// echo $pgnt_text;
        	
            // Split the pages and put them in an array
            $pages = explode('{pagebreak}', $pgnt_text);  	// print_r($pages);
            
            // Lets add empty space at the beginning of the array, Saves some actions further down the line.
            array_unshift($page_titles, "");		 // print_r($page_titles);
            array_unshift($pages, "");		 // print_r($pages);
            
            // Determine which page to display based on current url
            $trackerdata = trim($SESS->tracker['0'], '/'); // remove beginning and trailing slashes
            $location = explode('/', $trackerdata);		// print_r($location);
            $url_segments = count($location);		// print_r($url_segments);
            $final_segment = $location[$url_segments - 1]; // determine the last segment of the url
            
            

            // Does the last segment refer to a specific page?
            $page = '';
            $current_page = substr($final_segment, 1);
        	if(strpos($final_segment,'P') !== FALSE && is_numeric($current_page))  // if( preg_match('/^[P][0-9]+$/i', $final_segment) )
        	{
            	// We need a specific page - which?
            	if(array_key_exists($current_page, $pages))
            	{
            		// EE confuses pagebreaks with paragraphs, so some unwanted p tags may need to go		
            		$page .= $this->PageTidy($pages[$current_page]);
            	}
            	else
            	{
            		// Since this page doesn't excist we need to return something right?
            		$this->return_data = "<strong>Error: This page does not appear to exist.</strong>\n";
            		return;
            	}
            	
            	// Determine the base URL of the overall document
            	$pagenav_url = '';
            	foreach($location as $key => $val)
            	{
            		if($val != $final_segment)
            		{
            			$pagenav_url .= $val . "/";
            		}
            	}	// echo $pagenav_url;            	
            	$document_root = $FNS->create_url( "/".$pagenav_url );	
				
            	// What would the next and previous page's URL be?	
				$nextpagenum = $current_page + 1;
				$prevpagenum = $current_page - 1;
				$nextpage_url = $FNS->create_url( "/".$pagenav_url."P".$nextpagenum."/" );
				if($prevpagenum > 1)
				{
					// other pages need the number appended
					$prevpage_url = $document_root."P".$prevpagenum."/";
				}
				else 
				{ 
					// no need for 'P1' to be appended to the url, UGLY
					$prevpage_url = $document_root;
				}
            }
        	else 
        	{
            	// No page requested in the url; print page 1
            	$current_page = 1;
            	$page .= $this->PageTidy($pages[1]);
            	// What would the next and previous page's URL be?
            	$document_root = $FNS->create_url($SESS->tracker['0']);
            	$nextpage_url = $document_root."P2/";
            	$prevpage_url = '';
            }
            
            // Lets replace the {pgnt_current_page_title} with the current page title INSIDE of the template
   			$TMPL->template = str_replace("{pgnt_current_page_title}",$page_titles[$current_page], $TMPL->template);
   			
   			// Page numbers for the next and previous pages
            $next_page = $current_page + 1;	
			$prev_page = $current_page - 1;   			
   			
		    // Temp solution, since in the next code Page 1 will get /P1/, we don't want that!!
            // TODO: Find a better oslution for this!!
            if ($prev_page === 1)
            {
            	$TMPL->tagdata = str_replace("{pgnt_prev_page_url}", $document_root, $TMPL->tagdata);
            }
   			
   			// Lets replace a bunch of stuff
   			$TMPL->tagdata = str_replace(array( "{pgnt_current_page_title}",
            								    "{pgnt_next_page_title}",
            									"{pgnt_next_page_url}",
            									"{pgnt_prev_page_title}",
            									"{pgnt_prev_page_url}"),
   										array(   $page_titles[$current_page],
            									(isset($page_titles[$current_page + 1]))  ? $page_titles[$current_page + 1] : '',
            									(isset($page_titles[$current_page + 1]))  ? $document_root."P". $next_page ."/" : '',
            									(isset($page_titles[$current_page - 1]))  ? $page_titles[$current_page - 1] : '',
            									(isset($page_titles[$current_page - 1]))  ? $document_root."P". $prev_page ."/" : ''
            								  ),
            							$TMPL->tagdata);
        }
        else 
        {
        	// No pages where added :'(
            $page = $pgnt_text;
            
            // Remove {pgnt_current_page_title}
            $TMPL->template = str_replace("{pgnt_current_page_title}",'', $TMPL->template);
            $TMPL->tagdata  = str_replace("{pgnt_current_page_title}",'', $TMPL->tagdata);
        }
        
        // Remove the {pgnt_text} variable pair and replace it with the current page
        $TMPL->tagdata = preg_replace("/".LD."pgnt_text".RD."(.*?)".LD.SLASH.'pgnt_text'.RD."/s", $page, $TMPL->tagdata);
        
		// We are greedy with memory, so lets destroy unused stuff
		unset($pgnt_text, $page, $pages, $trackerdata, $location, $url_segments, $final_segment);
	}

	
	
	/*
	 * If they added the {pgnt_titles} variable pair lets do our stuffs
	 */
	if ($pgnt_titles)
	{
    	// Lets replace the variables with values in a loop
		$pgnt_titles_result = '';   
		$pgnt_titles_page = 0;      
        foreach ($pagebreak_matches[0] as $key => $value)
        {
        	// Increment page number on each loop
        	$pgnt_titles_page++;
        	
        	// If page number is more then 1, lets add /P*/, else lets keep out the /P*/
            if ($key > 0)
            {
	            $pgnt_titles_internal = str_replace(array("{pgnt_title}","{pgnt_url}", "&#47;"), array($page_titles[$key + 1],$document_root."P{$pgnt_titles_page}/", "/"), $pgnt_titles);
	            $pgnt_titles_result .= $pgnt_titles_internal;
	            
            	// Lets replace the {pgnt_current} variable
				if ($pgnt_titles_page == $current_page)
	            {
	            	$pgnt_titles_result = str_replace("{pgnt_current}",$current, $pgnt_titles_result);            	             		
	            }
	            else 
	            {
	            	$pgnt_titles_result = str_replace("{pgnt_current}",'', $pgnt_titles_result);   
	            }
        	}
			else
			{
				$pgnt_titles_internal = str_replace(array("{pgnt_title}","{pgnt_url}", "&#47;"), array($page_titles[$key + 1],$document_root, "/"), $pgnt_titles);
				$pgnt_titles_result .= $pgnt_titles_internal;
				
				// Lets replace the {pgnt_current} variable.
				if ($pgnt_titles_page == $current_page)
	            {
	            	$pgnt_titles_result = str_replace("{pgnt_current}",$current, $pgnt_titles_result);            	             		
	            }
	            else 
	            {
	            	$pgnt_titles_result = str_replace("{pgnt_current}",'', $pgnt_titles_result);   
	            }
			}
			

		}	// echo $pgnt_titles_result;
		
		$TMPL->tagdata = preg_replace("/".LD."pgnt_titles".RD."(.*?)".LD.SLASH.'pgnt_titles'.RD."/s", $pgnt_titles_result, $TMPL->tagdata);
        
		// We are greedy with memory, so lets destroy unused stuff
        unset($pagebreak_matches, $pgnt_titles_result, $pgnt_titles_page, $pgnt_titles_internal, $current);
	}
	
	// A quick test to see if the variables are not set, (the variable are not set if there are no pages found.)
	if (!isset($next_page))
	{
    	$next_page = 0;	
		$prev_page = 0;  		
	}
	
	// Lets do conditionals!!!
	$cond = array();	
	$cond['pgnt_next_page'] = ($next_page <= $pages_amount) ? 'TRUE' : 'FALSE';
	$cond['pgnt_prev_page'] = ($prev_page >= 1) ? 'TRUE' : 'FALSE';
	$cond['pgnt_pages']		= ($pages_amount > 0) ? 'TRUE' : 'FALSE';
	$TMPL->tagdata = $FNS->prep_conditionals($TMPL->tagdata, $cond);
	
	// We are greedy with memory, so lets destroy unused stuff
	unset($pages_amount,$cond, $next_page, $prev_page);            

	// Lets return the page
    $this->return_data = $TMPL->tagdata;
  }

  
  // An internal function which removes unwanted paragraph tags from pages
  function PageTidy($data)
  {
	$data = trim($data);
	if( substr($data, -3, 3) == '<p>' ) { // remove trailing <p> tag
		$data = substr($data, 0, strlen($data) - 3);
	}
	if( substr($data, 0, 4) == '</p>' ) { // remove </p> prefix
		$data = substr($data, 4, strlen($data));
	}
	return $data;
  }
  // ----------------------------------------
  //  Plugin Usage
  // ----------------------------------------

  // This function describes how the plugin is used.
  //  Make sure and use output buffering

  function usage()
  {
  ob_start(); 
  ?>
Lets you paginate an entry with table of contents (page titles)

In an entry just put: 
{pagebreak:Some title}
everywhere you would want a pagebreak, the plugin will fetch the title from the variable.


#############################
### Parameters: #############
#############################
-current=""
-The content of the parameter replaces the {pgnt_current} variable
-Ex. current="class='current'" (remember to balance quotes)


#############################
### Variable Pairs: #########
#############################
-{pgnt_text} {/pgnt_text}
-Place in between these variables the text you would want paginated. (REQUIRED)
-{pgnt_titles} {/pgnt_titles}
-Place in between these variables <li> or <select> etc


#############################
### Conditionals ############
#############################
-{if pgnt_pages} {/if}
-If there are any pages. (sometimes you only have an one page article)
-{if pgnt_prev_page} {/if}
-If there is a previous page
-{if pgnt_next_page} {/if}
-If there is a next page


#############################
### Variables ##############
#############################
-{pgnt_url}
-The full url to the corresponding page
-Will only work inside {pgnt_titles} {/pgnt_titles}
-{pgnt_title}
-The title of the page that was fetched from the to be paginated text.
-Will only work inside {pgnt_titles} {/pgnt_titles}
-{pgnt_current}
-If there current item is the current page. (you need to use the current="" paramater)
-Will only work inside {pgnt_titles} {/pgnt_titles}
-{pgnt_current_page_title}
-The page title of the current page
-Will work ANYWHERE inside your template, even outside the plugin tag.

-{pgnt_prev_page_title}
-The title of the previous page
-Advisable to use with {if pgnt_prev_page} {/if}
-{pgnt_prev_page_url}
-The url of the previous page
-Advisable to use with {if pgnt_prev_page} {/if}
-{pgnt_next_page_title}
-The title of the next page
-Advisable to use with {if pgnt_next_page} {/if}
-{pgnt_next_page_url}
-The url of the next page
-Advisable to use with {if pgnt_next_page} {/if}


#############################
### Simple Example: ########
#############################
{exp:paginatee}

<h1>{pgnt_current_page_title}</h1>

    {pgnt_text}
        {body}
    {/pgnt_text}

    <ul>
        {pgnt_titles}
        <li><a href="{pgnt_url}" title="Page {pgnt_title}">{pgnt_title}</a></li>
        {/pgnt_titles}        
    </ul>

{/exp:paginatee}

#############################
### Full Blown Example: #####
#############################
<html>
<head><title>{title}: {pgnt_current_page_title} </title></head>
<body>

{exp:weblog:entries weblob="default" url_title="{segment_3}"}

<h1>{title}: {pgnt_current_page_title}</h1>

{exp:paginatee current="class='current'"}

{pgnt_text}
    {body}
{/pgnt_text}
    
{if pgnt_pages}
<ul>
    {pgnt_titles}
    <li><a href="{pgnt_url}" title="Page {pgnt_title}" {pgnt_current}>{pgnt_title}</a></li>
    {/pgnt_titles}        
</ul>
{/if}

{if pgnt_prev_page}
    Previous Page: <a href="{pgnt_prev_page_url}">{pgnt_prev_page_title}</a>
{/if}

{if pgnt_next_page}
    Next Page: <a href="{pgnt_next_page_url}">{pgnt_next_page_title}</a>
{/if}
    
{/exp:paginatee}

{/exp:weblog:entries}


</body>
</html> 

  <?php
  $buffer = ob_get_contents();
	
  ob_end_clean(); 

  return $buffer;
  }
  // END

}

?>